package com.heeexy.example.controller.web;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.heeexy.example.service.LoginService;
import com.heeexy.example.service.SysLoginService;
import com.heeexy.example.service.TokenService;
import com.heeexy.example.service.UserService;

import com.heeexy.example.util.javaSendMail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import yinwei.bo.base.util.JwtUtils;
import yinwei.bo.common.Constants.Constans;
import yinwei.bo.common.entry.uList;
import yinwei.bo.common.entry.vo.loginVo;
import yinwei.bo.common.exception.Assert;
import yinwei.bo.common.result.R;
import yinwei.bo.common.result.ResponseEnum;
import yinwei.bo.common.util.*;
import yinwei.bo.common.util.uuid.Idutils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("User")
@CrossOrigin
public class UserLoginController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Value("${yaomi.captchaType}")
    private String captchaType;

    @Resource
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private UserService userService;

    @Autowired
    private JavaMailSender javaMailSender;
    @Resource
    private SysLoginService loginService;

    @RequestMapping("/Sign")
    public R register(@RequestBody uList ulist) {
        uList user=userService.findUser(ulist.getAccout());
        Assert.notEquals(user.getAccout(),ulist.getAccout(),ResponseEnum.USERNAME_EXIST);
        Assert.notEquals(ulist.getPhone(),user.getPhone(),ResponseEnum.MOBILE_EXIST_ERROR);
        userService.register(ulist);
        return R.ok().message("注册成功");
    }

    @RequestMapping("yLogin")
    public R yLogin(){

        return R.ok();
    }
    @RequestMapping("Login")
    public R login(@RequestBody loginVo loginVo){
        Map<String,Object> map=new HashMap<>();
        String token = loginService.login(loginVo.getUaccount(), loginVo.getUpwd(), loginVo.getCode(),
                loginVo.getUuid());
        map.put(Constans.LOGIN_SUCCESS,"success");
        map.put(Constans.TOKEN,token);
        return R.ok().data(map);
    }
    @GetMapping("getInfo")
    public R getInfo()
    {
        String usernameFromToken = JwtUtils.getUserName(tokenService.getToken(ServletUtils.getRequest()));
        //System.out.println("namekey"+usernameFromToken);
        String userKey = tokenService.getTokenKey(usernameFromToken);
        uList user = redisCache.getCacheObject(userKey);
        //System.out.println("user"+user);
        /*uList loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        uList user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);

        Map<String,Object> map=new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permissions", permissions);*/
        Map<String,Object> map=new HashMap<>();
        map.put("user",user);
        return R.ok().data(map);
    }
    @RequestMapping("/captcha")
    public R captcha(@RequestBody Map<String,String> map){
        String mobile = map.get("mobile");
        String code=RandomUtils.getFourBitRandom();
        // 校验手机号是否为空
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        // 校验邮箱是否合法

        //Assert.isTrue(RegexValidateUtils.checkEmail(mobile),ResponseEnum.EMAIL_ERROR);
        /*// 按断手机号是否已经被注册（这是一次远程调用）
        boolean result = coreUserInfoClient.checkMobile(mobile);
        Assert.isTrue(!result, ResponseEnum.MOBILE_EXIST_ERROR);*/
        redisTemplate.opsForValue().set("xyw:sms:code:" + mobile, code, 5, TimeUnit.MINUTES);
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        simpleMailMessage.setFrom("1689521269@qq.com");
        simpleMailMessage.setTo(mobile);
        simpleMailMessage.setSubject("验证码");
        simpleMailMessage.setText(code);
        javaMailSender.send(simpleMailMessage);
        return R.ok().message("发送成功");
    }
    @GetMapping("/captchaImage")
    public R getCode(HttpServletResponse response) throws IOException
    {
        // 保存验证码信息
        String uuid = Idutils.simpleUUID();
        String verifyKey = Constans.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;
        // 生成验证码
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            System.out.println(capText);
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constans.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return R.error().message(e.getMessage());
        }
        Map<String,Object> imgResult = new HashMap<String,Object>(2);
        imgResult.put("uuid", uuid);
        imgResult.put("img", base64.encode(os.toByteArray()));
        return R.ok().data(imgResult);
    }

    @RequestMapping("logout")
    public R logout(HttpServletRequest request){
        String usernameFromToken = JwtUtils.getUserName(tokenService.getToken(ServletUtils.getRequest()));

        String userKey = tokenService.getTokenKey(usernameFromToken);
        redisCache.deleteObject(userKey);
        return R.ok();
    }

    @GetMapping("/checkMobile/{mobile}")
    public boolean checkMobile(@PathVariable String mobile) {
        return userService.checkMobile(mobile);
    }

}


